<template>
    <div class="todo-container">
        <div class="todo-wrap">
            <Header :addTodo="addTodo"/>
            <List :todos="todos" :delTodo="delTodo" :updateTodo="updateTodo"/>
            <Footer :todos="todos" :checkAll="checkAll" :clearComplatedTodos="clearComplatedTodos"/>
        </div>
    </div>
</template>
<script lang="ts">
import Header from './components/header.vue'
import List from './components/list.vue'
import Footer from './components/footer.vue'
import {saveTodos, readTodos} from './utils/localStorageUtils'
import { defineComponent, onMounted, reactive, toRefs, watch } from 'vue'
// 引入接口
import {Todo} from './types/todo'
export default defineComponent({
    name: 'App',
    components: {
        Header,
        List,
        Footer
    },
    // 数据应该用数组来存储，数组中的每个数据都是一个对象，对象中应该有三个属性（id,title,isComplated）
    // 把数据定义在父级组件
    setup() {
        // const state = reactive<{todos: Todo []}>({
        //     todos: [{
        //         id:1,title: '111',isComplated: false
        //     },{
        //         id:2,title: '222',isComplated: true
        //     },{
        //         id:3,title: '333',isComplated: true
        //     }]
        // })
        const state = reactive<{todos: Todo []}>({
            todos: []
        })
        // 界面加载完毕后再读取数据
        onMounted(()=> {
            setTimeout(()=>{
                state.todos = readTodos()
            }, 1000)
        })
        // 添加数据的方法
        const addTodo = (todo:Todo) => {
            state.todos.unshift(todo)
        }
        // 删除数据的方法
        const delTodo = (index:number) => {
            state.todos.splice(index, 1)
        }
        // 修改todo的isComplated属性的状态
        const updateTodo = (todo:Todo,isComplated:boolean) => {
            todo.isComplated = isComplated
        }
        // 全选/全不选
        const checkAll = (isComplated:boolean) => {
            // 比较数组
            state.todos.forEach(todo => {
                todo.isComplated = isComplated
            })
        }
        // 清理所有选中的数据
        const clearComplatedTodos = () => {
             state.todos = state.todos.filter(item => !item.isComplated)
        }
        // 监视操作：如果todos数组的数据变化了，直接存储到缓存中
        // watch(()=> state.todos, (value) => {
        //     // 保存到浏览器缓存中
        //     localStorage.setItem('todos_keys', JSON.stringify(value))
        // }, {deep: true})

        // watch(
        //     ()=> state.todos,
        //     (value) => {
        //     saveTodos(value)
        // }, {deep: true})
        watch(()=> state.todos, saveTodos, {deep: true})
        return {
            ...toRefs(state),
            addTodo,
            delTodo,
            updateTodo,
            checkAll,
            clearComplatedTodos
        }
    },
})
</script>
<style scoped>
   .todo-container {
        width: 600px;
        margin: 0 auto;
   }
   .todo-container .todo-wrap {
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 5px;
   }
</style>